<template>
  <div class="add-equip-detail">
    <div class="add-equip-content">
      <px-button style="margin: 16px 0 -4px" type="primary" icon="ArrowLeft" @click="backMainPage">返回</px-button>
      <px-form ref="formRef" inline :model="formValue" :rules="rules" label-position="right" label-width="120px">
        <EditDropDown dropdownTitle="基础信息">
          <template v-slot:content>
            <px-row style="width: 100%">
              <px-col :span="12" style="width: 100%">
                <px-form-item label="报警时间" prop="alarmTime">
                  <px-date-picker
                    v-model="formValue.alarmTime"
                    style="width: 100%"
                    format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    type="datetime"
                    :disabled-date="disabledDate"
                    placeholder="请选择报警时间"
                  />
                </px-form-item>
              </px-col>
              <px-col :span="12">
                <px-form-item label="地块" prop="factoryAreaCode">
                  <px-select v-model="formValue.factoryAreaCode" filterable placeholder="请选择地块" clearable @change="handleGetFacName">
                    <px-option v-for="item in facCodeList" :key="item.id" :label="item.name" :value="item.value" />
                  </px-select>
                </px-form-item>
              </px-col>
            </px-row>
            <px-row style="width: 100%">
              <px-col :span="12">
                <px-form-item label="责任区" prop="responsibleZone">
                  <px-cascader
                    ref="cascaderRef"
                    v-model="formValue.responsibleZone"
                    :disabled="!formValue.factoryAreaCode"
                    filterable
                    clearable
                    style="width: 100%"
                    :options="areaList"
                    :props="cascaderProps"
                    placeholder="请选择责任区"
                    collapse-tags
                    collapse-tags-tooltip
                    @change="handleGetCommander"
                  />
                </px-form-item>
              </px-col>
              <px-col :span="12">
                <px-form-item label="应急指挥官" prop="commander">
                  <px-select-v2
                    v-model="formValue.commander"
                    :disabled="!formValue.responsibleZone"
                    multiple
                    filterable
                    clearable
                    :reserve-keyword="false"
                    :options="approvalList"
                    placeholder="请选择应急指挥官"
                    @change="commanderChange"
                  />
                </px-form-item>
              </px-col>
            </px-row>
            <px-row style="width: 100%">
              <px-col :span="12">
                <px-form-item label="事件类型" prop="alarmType">
                  <px-select v-model="formValue.alarmType" placeholder="请选择事件类型" clearable filterable @change="handleGetFile">
                    <px-option v-for="item in eventList" :key="item.id" :label="item.name" :value="item.value" />
                  </px-select>
                </px-form-item>
              </px-col>
              <px-col :span="12">
                <px-form-item label="文档名称" prop="docId">
                  <px-select
                    v-model="formValue.docId"
                    :disabled="!formValue.alarmType"
                    placeholder="请选择文档名称"
                    multiple
                    clearable
                    filterable
                    @change="fileChange"
                  >
                    <px-option v-for="item in fileList" :key="item.id" :label="item.documentName" :value="item.fileId" />
                  </px-select>
                </px-form-item>
              </px-col>
            </px-row>
            <px-row style="width: 100%">
              <px-col :span="24">
                <px-form-item label="事件说明" prop="alarmContent">
                  <px-input
                    v-model="formValue.alarmContent"
                    type="textarea"
                    :autosize="{ minRows: 2, maxRows: 4 }"
                    maxlength="1000"
                    placeholder="请输入事件说明"
                    clearable
                  />
                </px-form-item>
              </px-col>
            </px-row>
            <px-row style="width: 100%">
              <px-col :span="24">
                <px-form-item label="录音" prop="recordingFile">
                  <FileUpload
                    fileType="edit"
                    :countLimit="1"
                    :fileAccept="'.wav,.mp3'"
                    :fileList="formValue.recordingFile"
                    :fileData="{ moduleName: 'eqp' }"
                    @changeFileList="changeFileList"
                    @saveFileStatus="saveFileStatus"
                  />
                  <!-- 按钮 -->
                  <!-- <div>
                    <px-button @click="recOpen">打开录音,请求权限</px-button>
                    <px-button @click="recStart">开始录音</px-button>
                    <px-button @click="recStop">结束录音</px-button>
                    <px-button @click="recPlay">本地试听</px-button>
                  </div> -->
                  <!-- 波形绘制区域 -->
                  <!-- <div style="border: 1px solid #ccc; display: inline-block; vertical-align: bottom">
                    <div ref="recwave" style="height: 100px; width: 300px" />
                  </div> -->
                </px-form-item>
              </px-col>
            </px-row>
          </template>
        </EditDropDown>
      </px-form>
      <div class="info-form-btns">
        <px-button @click="backMainPage">取消</px-button>
        <px-button type="primary" :disabled="fileStatusFlag" @click="handleSubmit(formRef)">保存</px-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { queryDictData } from "@/api/common";
import { addAlarmEvent, editAlarmEvent, getAlarmEvent, getAlarmEventDetail } from "@/api/erc/alarm";
import { queryCheckAreaTree } from "@/api/erc/inspectPlan";
import FileUpload from "@/components/Upload/FileUpload.vue";
import { getEmployeeIdAndName } from "@/utils/pengxi";
import EditDropDown from "@/views/all/equip/components/EditDropDown.vue";
import { downloadPic } from "@visual/api/api";
import { PxMessage } from "px-ui";
import dayjs from "dayjs";
import { computed, reactive, ref, toRefs, watchEffect } from "vue";

/** TODO在线录音相关，当前因为http环境暂不支持 */
//必须引入的核心
// import Recorder from "recorder-core";
// //引入mp3格式支持文件；如果需要多个格式支持，把这些格式的编码引擎js文件放到后面统统引入进来即可
// import "recorder-core/src/engine/mp3";
// import "recorder-core/src/engine/mp3-engine";
// //录制wav格式的用这一句就行
// import "recorder-core/src/engine/wav";
// //可选的插件支持项，这个是波形可视化插件
// import "recorder-core/src/extensions/waveview";
// //ts import 提示：npm包内已自带了.d.ts声明文件（不过是any类型）

// 调用父级-返回主页、查询列表方法
const emits = defineEmits(["backMainPage", "queryTable"]);
// 父级传过来的值
const props = defineProps(["pageType", "alarmId"]);

const cascaderProps = {
  children: "children",
  label: "name",
  value: "id"
  // checkStrictly: true,
  // multiple: true
};

const formRef = ref();
const cascaderRef = ref();

const state = reactive<any>({
  formValue: {
    factoryAreaCode: "",
    alarmTime: dayjs(Date.now()).format("YYYY-MM-DD HH:mm:ss")
  },
  fileStatusFlag: false,
  executorInfoList: [], // 运维组列表
  docInfoList: [], // 运维组列表
  approvalList: [],
  eventList: [],
  fileList: [],
  facCodeList: [],
  areaList: [] // 责任区
});
const { formValue, fileStatusFlag, executorInfoList, docInfoList, approvalList, eventList, fileList, facCodeList, areaList } = toRefs(state);

// 表单校验规则
const rules = computed(() => ({
  alarmType: [{ required: true, message: "事件类型不能为空", trigger: "change" }],
  factoryAreaCode: [{ required: true, message: "地块不能为空", trigger: "change" }],
  responsibleZone: [{ required: true, message: "责任区不能为空", trigger: "change" }],
  commander: [{ required: true, message: "责任区不能为空", trigger: "change" }],
  alarmContent: [{ required: true, message: "事件说明不能为空", trigger: "change" }],
  alarmTime: [{ required: true, message: "报警时间不能为空", trigger: "change" }],
  // recordingFile: [{ required: true, message: "录音不能为空", trigger: "blur" }],
  docId: [{ required: true, message: "文档名称不能为空", trigger: "blur" }]
}));

// 责任人多选
const commanderChange = val => {
  executorInfoList.value = [];
  val.map(item => {
    approvalList.value.forEach(people => {
      if (people.userId === item) {
        executorInfoList.value.push({ id: people.userId, phone: people.phone, commanderName: `${people.empNo}-${people.realName}` });
      }
    });
  });
};

const fileChange = val => {
  docInfoList.value = [];
  val.map(item => {
    fileList.value.forEach(file => {
      if (file.fileId === item) {
        docInfoList.value.push({ docName: file.documentName, docId: file.fileId });
      }
    });
  });
};

// 根据所选区域获取指挥官列表
const handleGetCommander = () => {
  console.log(cascaderRef.value.getCheckedNodes());
  const list = cascaderRef.value.getCheckedNodes()[0]?.data?.responsiblePersonList;
  console.log(list);
  if (list && list?.length !== 0) {
    executorInfoList.value = list;
    formValue.value.commander = list?.map(item => item?.id) || [];
  }
};

// 根据选中的值获取厂区名字
const handleGetFacName = val => {
  if (val) {
    const filterItem = facCodeList.value.find(item => item.value === val);
    formValue.value.factoryAreaName = filterItem.name;
  }
  formValue.value.responsibleZone = [];
  executorInfoList.value = [];
  formValue.value.commander = [];
  getArea();
};

const disabledDate = (time: Date) => {
  return time.getTime() < Date.now() - 86400000; // 禁用今天之前的日期
};

const handleGetFile = async val => {
  formValue.value.recordingFile = [];
  fileList.value = await getAlarmEvent({ eventType: val });
};

// 新的文件列表
const changeFileList = async val => {
  formValue.value.recordingFile = val;
};
// 文件是否上传完，是否可以保存
const saveFileStatus = val => {
  fileStatusFlag.value = val;
};

const getArea = async () => {
  areaList.value = [];
  if (formValue.value.factoryAreaCode) {
    areaList.value = await queryCheckAreaTree({
      facCode: formValue.value.factoryAreaCode
    });
  }
};

const handleInitData = async () => {
  approvalList.value = await getEmployeeIdAndName();
  eventList.value = await queryDictData({ typeCode: "event_type_manual" });
  facCodeList.value = await queryDictData({ typeCode: "ERC_FACTORY_AREA" });
};

watchEffect(async () => {
  await handleInitData();
  if (props.pageType === "EDIT") {
    const detail = await getAlarmEventDetail({ alarmId: props.alarmId });
    const { commanderList, alarmType, docList } = detail;
    await handleGetFile(alarmType);
    executorInfoList.value = commanderList;
    docInfoList.value = docList;
    const list = commanderList?.map(item => item.id);
    const fileList = docList?.map(item => item.docId);
    const file = await downloadPic({ ids: [detail.recordingFile] });
    formValue.value = { ...detail, recordingFile: file, commander: list, docId: fileList };
    await getArea();
  }
});
// 返回主页面
const backMainPage = () => {
  formRef.value.resetFields();
  emits("backMainPage");
  // PxMessageBox.confirm(`确认退出工单吗？退出后内容将不会保存，请谨慎操作`, "提示", {
  //   confirmButtonText: "确认",
  //   cancelButtonText: "取消",
  //   type: "warning"
  // })
  //   .then(async () => {
  //     formRef.value.resetFields();
  //     emits("backMainPage");
  //   })
  //   .catch(() => {});
};

// 提交
const handleSubmit = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (valid) {
      const tempParams = JSON.parse(JSON.stringify(formValue.value));
      const { recordingFile, responsibleZone, factoryAreaCode } = tempParams;
      const recordArr = [];
      if (recordingFile && recordingFile.length > 0) {
        recordingFile.forEach(item => {
          if (item?.id) {
            recordArr.push(item.id);
          } else if (item?.response.data.id) {
            recordArr.push(item.response.data.id);
          }
        });
      }
      // 删除多余的字段
      delete tempParams.docId;
      delete tempParams.commander;
      const filterItem = facCodeList.value.find(item => item.value === factoryAreaCode);
      tempParams.factoryAreaName = filterItem.name;
      if (props.pageType === "ADD") {
        const params = {
          ...tempParams,
          recordingFile: recordArr?.join(","),
          commanderList: executorInfoList.value,
          docList: docInfoList.value,
          responsibleZone: responsibleZone[responsibleZone.length - 1]
        };
        await addAlarmEvent(params);
        PxMessage.success("创建成功");
        emits("backMainPage");
        emits("queryTable");
      } else if (props.pageType === "EDIT") {
        await editAlarmEvent({
          ...tempParams,
          recordingFile: recordArr?.join(","),
          commanderList: executorInfoList.value,
          docList: docInfoList.value,
          responsibleZone: Array.isArray(responsibleZone) ? responsibleZone[responsibleZone?.length - 1] : responsibleZone
        });
        PxMessage.success("编辑成功");
        emits("backMainPage");
        emits("queryTable");
      }
    }
  });
};

// let rec: any;
// let recBlob: any;
// let wave: any;
// const recwave = ref(null);
// // 打开录音
// const recOpen = () => {
//   //创建录音对象
//   rec = Recorder({
//     isUserNotAllow: false,
//     type: "wav", //录音格式，可以换成wav等其他格式
//     sampleRate: 16000, //录音的采样率，越大细节越丰富越细腻
//     bitRate: 16, //录音的比特率，越大音质越好
//     onProcess: (buffers: any, powerLevel: any, bufferDuration: any, bufferSampleRate: any, newBufferIdx: any, asyncEnd: any) => {
//       console.log("创建成功", buffers);
//       //录音实时回调，大约1秒调用12次本回调
//       //可实时绘制波形，实时上传（发送）数据
//       if (wave) {
//         wave.input(buffers[buffers.length - 1], powerLevel, bufferSampleRate);
//       }
//     }
//   });
//   if (!rec) {
//     alert("当前浏览器不支持录音功能！");
//     return;
//   }
//   //打开录音，获得权限
//   rec.open(
//     () => {
//       console.log("录音已打开");
//       if (recwave.value) {
//         //创建音频可视化图形绘制对象
//         wave = Recorder.WaveView({ elem: recwave.value });
//       }
//     },
//     (msg: any, isUserNotAllow: any) => {
//       //用户拒绝了录音权限，或者浏览器不支持录音
//       console.log((isUserNotAllow ? "UserNotAllow，" : "") + "无法录音:" + msg);
//     }
//   );
// };
// // 开始录音
// const recStart = () => {
//   if (!rec) {
//     console.error("未打开录音");
//     return;
//   }
//   rec.start();
//   console.log("已开始录音");
// };
// // 结束录音
// const recStop = () => {
//   if (!rec) {
//     console.error("未打开录音");
//     return;
//   }
//   rec.stop(
//     (blob: any, duration: any) => {
//       //blob就是我们要的录音文件对象，可以上传，或者本地播放
//       recBlob = blob;
//       //简单利用URL生成本地文件地址，此地址只能本地使用，比如赋值给audio.src进行播放，赋值给a.href然后a.click()进行下载（a需提供download="xxx.mp3"属性）
//       const localUrl = (window.URL || window.webkitURL).createObjectURL(blob);
//       console.log("录音成功", blob, localUrl, "时长:" + duration + "ms");
//       upload(blob); //把blob文件上传到服务器
//       rec.close(); //关闭录音，释放录音资源，当然可以不释放，后面可以连续调用start
//       rec = null;
//     },
//     (err: any) => {
//       console.error("结束录音出错：" + err);
//       rec.close(); //关闭录音，释放录音资源，当然可以不释放，后面可以连续调用start
//       rec = null;
//     }
//   );
// };
// // 上传录音
// const upload = (blob: any) => {
//   //使用FormData用multipart/form-data表单上传文件
//   //或者将blob文件用FileReader转成base64纯文本编码，使用普通application/x-www-form-urlencoded表单上传
//   // const form = new FormData();
//   // form.append('upfile', blob, 'recorder.mp3'); // 和普通form表单并无二致，后端接收到upfile参数的文件，文件名为recorder.mp3
//   // form.append('key', 'value'); // 其他参数
//   // var xhr = new XMLHttpRequest();
//   // xhr.open('POST', '/upload/xxxx');
//   // xhr.onreadystatechange = () => {
//   //   if (xhr.readyState == 4) {
//   //     if (xhr.status == 200) {
//   //       console.log('上传成功');
//   //     } else {
//   //       console.error('上传失败' + xhr.status);
//   //     }
//   //   }
//   // };
//   // xhr.send(form);
//   // 也可以写自己的上传函数
//   // uploadService(blob, "zengjiaqi_test.wav");
// };
// // 本地播放录音
// const recPlay = () => {
//   //本地播放录音试听，可以直接用URL把blob转换成本地播放地址，用audio进行播放
//   const localUrl = URL.createObjectURL(recBlob);
//   const audio = document.createElement("audio");
//   audio.controls = true;
//   document.body.appendChild(audio);
//   audio.src = localUrl;
//   audio.play(); //这样就能播放了
//   //注意不用了时需要revokeObjectURL，否则霸占内存
//   setTimeout(function () {
//     URL.revokeObjectURL(audio.src);
//   }, 5000);
// };
</script>

<style lang="scss" scoped>
@import url("@/views/all/equip/scss/add-detail.scss");
</style>
